"use strict";
import Vue from 'vue'
import request from '@/utils/request'
import {appBaseUrl} from '@/utils/request'
import { getToken} from "@/utils/auth"
import { stringFormat} from "@/utils/common";

// 图片链接生成
export function createImgUrl(data) {
  if(!data){
    return '';
  }
  // console.log(stringFormat('{0}/common/img?s={1}&t={2}&_a={3}', appBaseUrl, data.s, data.t, getToken()))
  return stringFormat('{0}/common/img?s={1}&t={2}&_a={3}', appBaseUrl, data.s, data.t, getToken());
}

// 文件下载链接生成
export function createFileUrl(data) {
  // console.log(stringFormat('{0}/common/file?s={1}&t={2}&_a={3}', appBaseUrl, data.s, data.t, getToken()))
  return stringFormat('{0}/common/file?s={1}&t={2}&_a={3}', appBaseUrl, data.s, data.t, getToken());
}

// 文件下载链接生成
export function createDownloadUrl(url, data) {
  let param = '';
  if(data && data instanceof Object){
    for(let key in data){
      param+= stringFormat('&{0}={1}', key, data[key])
    }
  }
  // console.log(stringFormat('{0}/common/file?s={1}&t={2}&_a={3}', appBaseUrl, data.s, data.t, getToken()))
  return stringFormat('{0}{1}?_a={2}{3}', appBaseUrl, url, getToken(), param);
}

// 通用下载方法
export function fileDownload(data) {
  window.location.href = createFileUrl(data);
}

// 下载
export function downloadFile(_op, callback) {
  var op = {
    method: 'get'
  };
  op = Object.assign(op, _op);
  request(op).then(response => {
    try {
      if (response && response.success && response.data) {
        if (response.data.t && response.data.s) {
          downloadFileHidden(response.data);
        } else {
          Vue.msgError("文件地址为空");
        }
      } else {
        Vue.msgError(response && response.msg ? response.msg : "文件下载失败");
      }
    } finally {
      if (callback && callback instanceof Function) {
        callback();
      }
    }
  }).catch(() => {});
}

export function commonDownload(params) {
  downloadFileHidden('/common/file', params)
}

export function downloadFileHidden(url, params) {
  var form = document.createElement("form");
  form.setAttribute("id", "_downloadform_");
  form.setAttribute("style", "display:none");
  form.setAttribute("target", "");
  form.setAttribute("method", "get");
  form.setAttribute("action", appBaseUrl + url);
  params = Object.assign({}, params);
  params._a = getToken();
  for (var key in params) {
    var input1 = document.createElement("input");
    input1.setAttribute("type", "hidden");
    input1.setAttribute("name", key);
    input1.setAttribute("value", params[key]);
    form.appendChild(input1);
  }
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

export default downloadFile

const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}

export function downLoadZip(str, filename) {
  var url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { 'Authorization': getToken() }
  }).then(res => {
    resolveBlob(res, mimeMap.zip)
  })
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

export function getFileFromUrl(url, fileName) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.setRequestHeader('Accept', 'image/jpeg');
        xhr.responseType = "blob";
        // 加载时处理
        xhr.onload = () => {
          // 获取返回结果
            let blob = xhr.response;
            // 返回结果
            resolve(new File([blob], fileName, { type: 'image/png' }));
        };
        xhr.onerror = (e) => {
            reject(e)
        };
        // 发送
        xhr.send();
    });
}
